package com.cqhz.quwan.ui.activity

import android.content.Intent
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.*
import com.cqhz.quwan.mvp.esport.ESportContract
import com.cqhz.quwan.mvp.esport.ESportPresenter
import com.cqhz.quwan.service.API
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.base.WebViewActivity
import com.cqhz.quwan.ui.adapter.ESportExpandableQuickAdapter
import com.cqhz.quwan.ui.interfaces.SelectTeamClickListener
import com.cqhz.quwan.ui.login.LoginActivity
import com.cqhz.quwan.ui.widget.LoadMoreDoneView
import com.cqhz.quwan.util.CommonDecoration
import com.cqhz.quwan.util.formatMoney
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import kotlinx.android.synthetic.main.activity_esport.*
import me.militch.quickcore.core.HasDaggerInject
import me.militch.quickcore.mvp.model.ModelHelper
import javax.inject.Inject


/**
 * 电竞
 * Created by Guojing on 2018/10/12.
 */
class ESportActivity : GoBackActivity(), ESportContract.View, HasDaggerInject<ActivityInject>, SelectTeamClickListener {

    @Inject
    lateinit var modelHelper: ModelHelper
    @Inject
    lateinit var eSportPresenter: ESportPresenter
    private var loginBean: LoginBean? = null
    private var titleList = ArrayList<TitleBean>()
    private var pagePosition: Int = 0// 当前页面位置
    private var pages = ArrayList<View>()
    private var holders = ArrayList<PageViewHolder>()
    private var adapters = ArrayList<ESportExpandableQuickAdapter>()
    private var games = ArrayList<ArrayList<ESportBean>>()
    private var esports = ArrayList<ArrayList<MultiItemEntity>>()
    private var lotteryId = ""

    override fun layout(): Int {
        return R.layout.activity_esport
    }

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun titleBarText(): String? {
        return "电竞"
    }

    override fun initView() {
        eSportPresenter.attachView(this)

        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo
            eSportPresenter.getUserInfo(loginBean!!.userId!!)
        }
        // 获取页面标题
        lotteryId = intent.getStringExtra(KeyContract.LotteryId)
        eSportPresenter.getTitleList(lotteryId)
        pagePosition = intent.getStringExtra(KeyContract.Position).toInt()
        setTitleBarText(intent.getStringExtra(KeyContract.Title))

        setTitleBarRightText("玩法") {
            val intent = Intent(this, WebViewActivity::class.java)
            intent.putExtra(KeyContract.Title, "电竞玩法")
            intent.putExtra(KeyContract.Url, API.rule)
            startActivity(intent)
        }
        action_goto_recharge.setOnClickListener { startActivity(Intent(this, if (loginBean == null) LoginActivity::class.java else RechargeActivity::class.java)) }
        action_goto_my_prediction.setOnClickListener { startActivity(Intent(this, if (loginBean == null) LoginActivity::class.java else MyPredictionActivity::class.java)) }
    }

    /**
     * 初始化列表适配器
     */
    private fun initAdapter() {
        // 当前页面的布局
        var pageView = LayoutInflater.from(this).inflate(R.layout.layout_page, vp_content, false) as View
        var holder = PageViewHolder(pageView)

        // 当前页面列表的空布局
        var emptyView = LayoutInflater.from(this).inflate(R.layout.layout_none, holder.rvContent.parent as? ViewGroup, false) as View
        var ivNone = emptyView.findViewById(R.id.iv_none) as ImageView
        ivNone.setImageResource(0)

        // 当前页面列表的数据和适配器
        var matchList = ArrayList<ESportBean>()
        var eSportList = ArrayList<MultiItemEntity>()
        var matchListAdapter = ESportExpandableQuickAdapter(this, eSportList, this)
        matchListAdapter.emptyView = emptyView
        matchListAdapter.setLoadMoreView(LoadMoreDoneView())

        // 当前页面列表适配器的事件
        holder.rvContent.layoutManager = LinearLayoutManager(this)
        holder.rvContent.addItemDecoration(CommonDecoration(1))
        holder.rvContent.adapter = matchListAdapter
        matchListAdapter.setOnLoadMoreListener({
            var currentPage = vp_content.currentItem
            if (games[currentPage].size > 0) {
                if (games[currentPage].size % KeyContract.pageSize == 0) {
                    var pageNo = games[currentPage].size / KeyContract.pageSize + 1
                    holders[currentPage].refreshLayout.isEnableRefresh = false
                    eSportPresenter.getGameList(pageNo, KeyContract.pageSize, titleList[pagePosition].type.toInt(), pagePosition)
                } else {
                    adapters[currentPage].loadMoreEnd()
                }
            } else {
                holders[currentPage].refreshLayout.isEnableRefresh = false
                eSportPresenter.getGameList(1, KeyContract.pageSize, titleList[pagePosition].type.toInt(), pagePosition)
            }
        }, holder.rvContent)

        // 刷新
        holder.refreshLayout.setOnRefreshListener { refreshCurrentPage() }

        // 将当前的页面、列表控件、数据列表、适配器加入相应的列表
        pages.add(pageView)
        holders.add(holder)
        games.add(matchList)
        esports.add(eSportList)
        adapters.add(matchListAdapter)
    }

    /**
     * 点击选择获胜队伍
     * @param  teamPosition 选中位置的坐标
     * @param  bean
     */
    override fun onTeamClick(teamPosition: Int, bean: ESportItemBean) {
        var intent = Intent(this, if (loginBean == null) LoginActivity::class.java else ESportDetailActivity::class.java)
        intent.putExtra(KeyContract.Title, bean.matchName)
        intent.putExtra("matchId", bean.matchId)
        intent.putExtra(KeyContract.LotteryId, lotteryId)
        startActivity(intent)
    }

    /**
     * 初始化页面
     */
    private fun initPager(titles: Array<String>) {
        vp_content.adapter = object : PagerAdapter() {
            override fun getCount(): Int {
                return pages.size
            }

            override fun isViewFromObject(view: View, `object`: Any): Boolean {
                return view === `object`
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                container.removeView(pages[position])
            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                var view = pages[position]
                var parent = view.parent as? ViewGroup
                parent?.removeAllViews()
                container.addView(view)
                return view
            }
        }
        st_tab.setViewPager(vp_content, titles)
        vp_content.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                pagePosition = vp_content.currentItem
                if (games[position].size <= 0) {
                    refreshCurrentPage()
                }
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }


    /**
     * 刷新当前页面
     */
    private fun refreshCurrentPage() {
        eSportPresenter.getGameList(1, KeyContract.pageSize, titleList[pagePosition].type.toInt(), pagePosition)
    }

    override fun setTitleList(list: ArrayList<TitleBean>) {
        // 初始化跳转页面
        titleList.clear()
        titleList.addAll(list)
        val titles: Array<String> = Array(titleList.size) { "" }
        for (i in 0 until titleList.size) {
            titles[i] = titleList[i].name
        }

        // 初始化页面元素和相应数据以及适配器
        for (i in 1..titles.size) {
            initAdapter()
        }
        initPager(titles)
        vp_content.currentItem = pagePosition
        refreshCurrentPage()
    }

    override fun requestTitleFail() {

    }

    override fun setBean(bean: String) {
        action_goto_recharge.text = bean.formatMoney()
    }

    override fun loadGameList(currentPage: Int, pageNo: Int, pageResultBean: PageResultBean<ESportBean>) {
        if (pageNo == 1) {
            games[currentPage].clear()
            esports[currentPage].clear()
            adapters[currentPage].setEnableLoadMore(true)
            if (holders[currentPage].refreshLayout.state.isHeader!!) {
                holders[currentPage].refreshLayout.finishRefresh()
            }
        }

        if (pageResultBean.records.isNotEmpty()) {
            for (i in 0 until pageResultBean.records.size) {
                var eSportBean = pageResultBean.records[i]
                for (j in 0 until pageResultBean.records[i].playList!!.size) {
                    var eSportItemBean = pageResultBean.records[i].playList!![j]
                    eSportItemBean.matchName = pageResultBean.records[i].matchName
                    eSportItemBean.type = pageResultBean.records[i].type
                    eSportBean.addSubItem(eSportItemBean)
                }
                games[currentPage].add(eSportBean)
                esports[currentPage].add(eSportBean)
            }
        }

        if (pageResultBean.total > games[currentPage].size) {
            adapters[currentPage].loadMoreComplete()
        } else {
            adapters[currentPage].loadMoreEnd()
        }

        // 刷新数据并且展开第一项
        if (pageNo == 1) {
            adapters[currentPage].expand(0)
        }
        adapters[currentPage].notifyDataSetChanged()
        holders[currentPage].refreshLayout.isEnableRefresh = true
    }

    internal class PageViewHolder(view: View) {
        var rvContent = view.findViewById(R.id.rv_content) as RecyclerView
        var refreshLayout = view.findViewById(R.id.refreshLayout) as SmartRefreshLayout
    }

    override fun onResume() {
        super.onResume()

        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo
            eSportPresenter.getUserInfo(loginBean!!.userId!!)
        } else {
            action_goto_recharge.text = "0.00"
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        eSportPresenter.detachView()
    }
}
